package cn.max.plat.utils;

import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 *@author Val.(Valentine Vincent) E-mail:valer@126.com
 *@version 1.0
 *@date 2011-11-19
 *Instruction :
 **/
public class Downloader {

	public static void downloadFile(HttpServletRequest req, HttpServletResponse resp, File file, String name, String contentType) {
		
		OutputStream os = getDownloadStream(req, resp, name, contentType);
		
		try {
			FileCopyUtils.copy(new FileInputStream(file), os);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void downloadFile(HttpServletRequest req, HttpServletResponse resp, File file, String name) {
		OutputStream os = getDownloadStream(req, resp, name, ContentTypeHelper.getContentType(file.getName()));
		
		try {
			FileCopyUtils.copy(new FileInputStream(file), os);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static OutputStream getDownloadStream(HttpServletRequest req, HttpServletResponse resp, String name, String contentType) {
		try {

			if (req.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
			    //IE
			    name = URLEncoder.encode(name, "UTF-8");
			}else {
			    //firefox/chrome
			    name = new String(name.getBytes("UTF-8"), "ISO8859-1");
			}

			resp.setHeader("Content-Disposition", "attachment;filename=" + name);
			resp.setContentType("application/x-gzip; charset=UTF-8");
			return resp.getOutputStream();
		} catch (IOException e) {
			return null;
		}
	}

}
